package com.gxc.dbcore.util;

import javax.servlet.http.HttpServletRequest;

public class PageInfo {

	private int pageSize;
	private int recordCount;
	private int pageCurrent;
	private int pageCount;

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getRecordCount() {
		return recordCount;
	}

	public void setRecordCount(int recordCount) {
		this.recordCount = recordCount;
	}

	public int getPageCurrent() {
		return pageCurrent;
	}

	public void setPageCurrent(int pageCurrent) {
		this.pageCurrent = pageCurrent;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public static PageInfo getFromRequest(HttpServletRequest request) {

		PageInfo pageInfo = new PageInfo();

		String recordCount = request.getParameter("recordCount");
		String pageSize = request.getParameter("pageSize");
		String pageCurrent = request.getParameter("pageCurrent");
		String pageCount = request.getParameter("pageCount");

		try {
			pageInfo.setRecordCount(Integer.valueOf(recordCount.trim()));
		} catch (Exception e) {
			pageInfo.setRecordCount(0);
		}
		try {
			pageInfo.setPageSize(Integer.valueOf(pageSize.trim()));
		} catch (Exception e) {
			pageInfo.setPageSize(10);
		}
		try {
			pageInfo.setPageCount(Integer.valueOf(pageCount.trim()));
		} catch (Exception e) {
			pageInfo.setPageCount(0);
		}
		try {
			pageInfo.setPageCurrent(Integer.valueOf(pageCurrent.trim()));
		} catch (Exception e) {
			pageInfo.setPageCurrent(1);
		}

		if (pageInfo.getPageCount() < 0) {
			pageInfo.setPageCount(0);
		}
		if (pageInfo.getPageCurrent() <= 0) {
			pageInfo.setPageCurrent(1);
		}
		if (pageInfo.getPageSize() <= 0) {
			pageInfo.setPageSize(20);
		}
		if (pageInfo.getRecordCount() < 0) {
			pageInfo.setRecordCount(0);
		}

		return pageInfo;
	}

	public void setByCount(int recordCount) {
		this.recordCount = recordCount;
		this.pageCount = (this.recordCount - 1) / this.pageSize + 1;
		if (this.pageCount <= 0) {
			this.pageCount = 1;
		}
		if (this.pageCurrent > this.pageCount) {
			this.pageCurrent = this.pageCount;
		}
	}

	public int getOffset() {
		return this.pageSize * (this.pageCurrent - 1);
	}
	
	public int getLimit() {
		return this.pageSize;
	}

}
